package com.ostrich.note.net;









import com.ostrich.note.entity.BaseResponseEntity;

import java.lang.reflect.Type;
import java.util.concurrent.atomic.AtomicBoolean;

import androidx.lifecycle.LiveData;
import retrofit2.Call;
import retrofit2.CallAdapter;
import retrofit2.Callback;
import retrofit2.Response;


public class LiveDataCallAdapter<T> implements CallAdapter<T, LiveData<T>> {

    private Type responseType;
    public LiveDataCallAdapter(Type responseType) {
        this.responseType = responseType;
    }
    @Override
    public Type responseType() {
        return responseType;
    }
    @Override
    public LiveData<T> adapt(Call<T> call) {

        return new LiveData<T>() {
            AtomicBoolean start = new AtomicBoolean(false);
            @Override
            protected void onActive() {
                super.onActive();
                if (start.compareAndSet(false, true)){
                    call.enqueue(new Callback<T>() {
                        @Override
                        public void onResponse(Call<T> call, Response<T> response) {
                            if (200 == response.code()) {
                                postValue(response.body());//设置属性
                            }else {
                                BaseResponseEntity apiResponse = new BaseResponseEntity(response.code(),response.message());
                                postValue((T) apiResponse);
                            }
                        }

                        @Override
                        public void onFailure(Call<T> call, Throwable t) {
                            BaseResponseEntity apiResponse = new BaseResponseEntity(404, t.getMessage());
                            postValue((T) apiResponse);
                        }
                    });
                }
            }
        };
    }



}
